package com.quectel.cms.config.redismsg;

import com.quectel.business.common.websocket.send.SendMsg;
import com.quectel.cms.config.websocket.SocketSessionUtils;
import com.quectel.constant.WebSocketConstants;
import com.quectel.util.common.JacksonUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * Redis订阅发布
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2023-05-18 19:36:00
 */
@Configuration
public class RedisMsgConfig implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        if (WebSocketConstants.CmsApi.MSG_SEND_TOPIC.equals(new String(pattern))) {
            String body = new String(message.getBody());
            SendMsg sendMsg = JacksonUtils.parse(body, SendMsg.class);
            SocketSessionUtils.sendMsg(sendMsg.getVillageId(), sendMsg.getMsgType(), sendMsg.getTitle(), sendMsg.getContent(), sendMsg.getExtParams());
        }
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory,
                                                   RedisMsgConfig listener
    ) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        // 订阅地址
        container.addMessageListener(listener, new ChannelTopic(WebSocketConstants.CmsApi.MSG_SEND_TOPIC));
        return container;
    }
}
